<template>
  <div class="container index-wrap">
    <headerBar
      :title="local.logoText"
      isHome="true"
      :isNoReturn="true"
      @changeLan="changeLan"
    ></headerBar>
    <div class="all" :style="{ paddingTop: pdt + 'px' }">
      <div class="top">
        <div class="top-name">
          <img
            style="width: 54rpx; height: 54rpx"
            class="userinfo-avatar"
            :src="avatarUrl"
            background-size="cover"
          />
          <div @click="bindViewTap">{{ nickName }}</div>
          <!--      userInfo.nickName-->
          <div v-if="phone">-</div>
          <div>{{ phone }}</div>
        </div>
        <div @click="routerToUrl('../../packageA/pages/msg/index')">
          <i class="iconfont icontongzhi2x msg-green">
            <span :class="redPot ? 'red' : ''"></span>
          </i>
        </div>
      </div>
      <div class="itemListContent">
        <div class="itemListBg"></div>
        <div class="itemList">
          <div class="item">
            <div class="main-title">{{ local.purchaseWarehousing }}</div>
            <div class="sub-title">
              <div
                class="a"
                @click="
                  routerToUrl('../../packageA/pages/purchaseReceipt/index')
                "
              >
                {{ local.warehousingList }}
              </div>
              <div
                class="a"
                @click="routerToUrl('../../packageA/pages/addStock/index')"
              >
                {{ local.add }}
              </div>
            </div>
          </div>
          <div class="item">
            <div class="main-title">{{ local.inventoryManagement }}</div>
            <div class="sub-title">
              <div
                class="a"
                @click="routerToUrl('../../packageA/pages/stockControl/index')"
              >
                {{ local.inventoryManagement }}
              </div>
            </div>
          </div>
          <div class="item">
            <div class="main-title">{{ local.productionManagement }}</div>
            <div class="sub-title">
              <div
                class="a"
                @click="routerToUrl('../../packageA/pages/splitRecords/index')"
              >
                {{ local.productionManagement }}
              </div>
              <div
                class="a"
                @click="
                  routerToUrl('../../packageA/pages/outStockControl/index')
                "
              >
                {{ local.productSplitting }}
              </div>
            </div>
          </div>
          <div class="item">
            <div class="main-title">{{ local.salesManagement }}</div>
            <div class="sub-title">
              <div
                class="a"
                @click="routerToUrl('../../packageA/pages/saleOrderList/index')"
              >
                {{ local.salesOrder }}
              </div>
              <div
                class="a"
                @click="routerToUrl('../../packageA/pages/addSaleOrder/index')"
              >
                {{ local.newSalesOrder }}
              </div>
            </div>
          </div>
          <div class="item">
            <div class="main-title">{{ local.logistics }}</div>
            <div class="sub-title">
              <div
                class="a"
                @click="routerToUrl('../../packageA/pages/logistics/index')"
              >
                {{ local.logisticsDistribution }}
              </div>
              <div
                class="a"
                @click="
                  routerToUrl('../../packageA/pages/logisticsTrace/index')
                "
              >
                {{ local.trace }}
              </div>
            </div>
          </div>
          <!-- <div class="item">
            <div class="main-title">{{local.statisticalReport}}</div>
            <div class="sub-title">
              <div
                class="a"
                @click="routerToUrl('../../packageA/pages/statisticalReport/index')"
              >{{local.importAnExportStatistics}}</div>
            </div>
          </div> -->
        </div>

        <div @click="logoutHandle" class="logout">{{ local.logout }}</div>
      </div>
      <div class="copy-right">© {{ local.copyright }}.</div>
      <div class="index-circle left-bottom-circle"></div>
      <div class="right-bottom-circle index-circle"></div>
      <div class="right-top-circle index-circle"></div>
      <!--      <canvas class='canvas' canvas-id='canvas' bindlongtap='save'></canvas>-->
    </div>
    <!--    二维码-->
    <!--    <canvas canvas-id="qrcode" height="300"></canvas>-->
  </div>
</template>

<script>
import card from '@/components/card'
import headerBar from '@/components/headerBar'
import wxbarcode from 'wxbarcode'
import home from '@/api/home'
import { pinyin } from '@/utils/hz2py_full'
export default {
  mpType: 'page',

  data() {
    return {
      pdt: 66,
      motto: 'Hello World',
      userInfo: {},
      good: {},
      local: wx.getStorageSync('local'),
      redPot: false,
      nickName: '',
      avatarUrl: '',
      phone: '',
    }
  },

  components: {
    card,
    headerBar,
  },
  onShow() {
    this.initLang()
  },
  onLoad(options) {
    this.initLang()
    if (wx.getStorageSync('informTypeCount') !== 0) {
      this.redPot = true
    }
    if (getCurrentPages().length > 8) {
    }
    const that = this
    that.initUserInfo(options)
    wx.getUserInfo({
      success: function (res) {
        var userInfo = res.userInfo
        that.nickName = userInfo.nickName
        that.avatarUrl = userInfo.avatarUrl
      },
    })
    this.phone = wx.getStorageSync('phone') == 'common.error' ? '' : this.phone
    this.getGoodId()
    this.draw()
    wx.getSystemInfo({
      success: (e) => {
        let info = wx.getMenuButtonBoundingClientRect()
        let CustomBar = info.bottom + info.top - e.statusBarHeight
        this.globalData.CustomBar = CustomBar
      },
    })
    this.pdt = this.globalData.CustomBar
    this.initData()
  },
  methods: {
    initLang() {
      this.local = wx.getStorageSync('local')
    },
    logoutHandle() {
      try {
        wx.clearStorageSync()
        wx.reLaunch({
          url: '/pages/login/index',
        })
        let lang = wx.getSystemInfoSync().language
        // 无语种时预设一个默认语言
        if (!wx.getStorageSync('local')) {
          let localList = require('../../utils/locales.js')
          if (lang == 'zh' || lang == 'zh_CN') {
            wx.setStorageSync('local', localList.localList.zh)
          } else {
            wx.setStorageSync('local', localList.localList.en)
          }
          wx.setStorageSync('lang', lang)
          // 调用API从本地缓存中获取数据
          const logs = wx.getStorageSync('logs') || []
          logs.unshift(Date.now())
          wx.setStorageSync('logs', logs)
        }
      } catch (e) {
        // Do something when catch error
      }
    },
    initData() {
      this.getBelt()
      this.getSupplierList()
      this.getBuyAreaList()
      this.getCustomerList()
      this.getUserList()
    },
    initUserInfo(options) {
      this.nickName = options.username
      this.avatarUrl = '/static/style/avatar.png'
    },

    //分组供应商
    pySortSupplier(arr) {
      var letters = 'ABCDEFGHJKLMNOPQRSTWXYZ'.split('')
      var result = []
      var curr
      for (var i = 0; i < letters.length; i++) {
        curr = { groupName: letters[i], users: [] }
        for (var j = 0; j < arr.length; j++) {
          let firstLetter = pinyin.go(arr[j].supplierName)
          var initial = firstLetter.charAt(0) // 截取第一个字符
          if (initial == letters[i] || initial == letters[i].toLowerCase()) {
            curr.users.push({
              id: arr[j].supplierId,
              name: arr[j].supplierName,
              phone: arr[j].supplierCode,
            })
          }
        }
        if (curr.users.length) {
          result.push(curr)
        }
      }
      return result
    },

    //分组客户
    pySortCustomer(arr) {
      var letters = 'ABCDEFGHJKLMNOPQRSTWXYZ'.split('')
      var result = []
      var curr
      for (var i = 0; i < letters.length; i++) {
        curr = { groupName: letters[i], users: [] }
        for (var j = 0; j < arr.length; j++) {
          let firstLetter = pinyin.go(arr[j].customerName)
          var initial = firstLetter.charAt(0) // 截取第一个字符
          if (initial == letters[i] || initial == letters[i].toLowerCase()) {
            curr.users.push({
              id: arr[j].customerId,
              name: arr[j].customerName,
              phone: arr[j].customerCode,
            })
          }
        }
        if (curr.users.length) {
          result.push(curr)
        }
      }
      return result
    },

    //获取用户列表，
    async getUserList() {
      const { rows } = await home.getCarUser({
        pageSize: 2000,
        pageNum: 1,
        status: 0,
      })
      wx.setStorageSync('userArray', rows)
    },

    //获取客户列表，将列表数据存储在storage
    async getCustomerList() {
      const { rows } = await home.getCustomerList({
        pageSize: 2000,
        pageNum: 1,
        status: 0,
      })
      let list = this.pySortCustomer(rows)
      wx.setStorageSync('customerArray', rows)
      wx.setStorageSync('customerList', list)
    },

    //获取供应商列表，将列表数据、分组后的数据都存储在storage
    async getSupplierList() {
      const { rows } = await home.getSupplierList({
        pageSize: 1000,
        pageNum: 1,
        status: 0,
      })
      let list = this.pySortSupplier(rows)
      wx.setStorageSync('supplierArray', rows)
      wx.setStorageSync('supplierList', list)
    },
    getBuyAreaList() {
      let buyAreaList = []
      // 获取采购区域
      home
        .getBuyArea({})
        .then(({ data }) => {
          buyAreaList = data
          wx.setStorageSync('buyAreaList', buyAreaList)
        })
        .catch((e) => {
          wx.setStorageSync('buyAreaList', buyAreaList)
          console.error(e)
        })
    },

    //获取皮带类型
    async getBelt() {
      const { rows, code, msg } = await home.getBeltLevel({
        dictType: 'beltType',
      })
      if (code == 0) {
        wx.setStorageSync('beltType', rows)
      } else {
        wx.showToast({
          title: msg,
          duration: 4000,
          icon: 'none',
        })
      }
      this.getLevel()
      this.getFrameType()
    },

    //获取框架类型
    async getFrameType() {
      const { rows, code, msg } = await home.getBeltLevel({
        dictType: 'frameType',
      })
      if (code == 0) {
        wx.setStorageSync('frameType', rows)
      } else {
        wx.showToast({
          title: msg,
          duration: 4000,
          icon: 'none',
        })
      }
    },

    //获取等级
    async getLevel() {
      const { rows, code, msg } = await home.getBeltLevel({
        dictType: 'goodsLevel',
      })
      if (code == 0) {
        wx.setStorageSync('goodsLevel', rows)
      } else {
        wx.showToast({
          title: msg,
          duration: 4000,
          icon: 'none',
        })
      }
      this.getHub()
    },
    //获取hub
    async getHub() {
      const { rows, code, msg } = await home.getBeltLevel({
        dictType: 'hubType',
      })
      if (code == 0) {
        wx.setStorageSync('hubType', rows)
      } else {
        wx.showToast({
          title: msg,
          duration: 4000,
          icon: 'none',
        })
      }
      this.getSteelReel()
    },
    //获取steelReel
    async getSteelReel() {
      const { rows, code, msg } = await home.getBeltLevel({
        dictType: 'steelReel',
      })
      if (code == 0) {
        wx.setStorageSync('steelReel', rows)
      } else {
        wx.showToast({
          title: msg,
          duration: 4000,
          icon: 'none',
        })
      }
      this.getPaymentStatus()
    },
    async getPaymentStatus() {
      const { rows, code, msg } = await home.getBeltLevel({
        dictType: 'paymentStatus',
      })
      if (code == 0) {
        wx.setStorageSync('paymentStatus', rows)
      } else {
        wx.showToast({
          title: msg,
          duration: 4000,
          icon: 'none',
        })
      }
    },
    changeLan(val) {
      this.local = val
    },
    async getGoodId() {
      // const { goodsName, goodsCode } = await home.getGoodId({id: 1})
      // let code = '7777777'
      wxbarcode.qrcode('qrcode', '1234566677777777776', 120, 120)
    },
    draw() {},
    routerToUrl(url) {
      wx.navigateTo({
        url,
      })
    },
    bindViewTap() {
      const url = '/packageA/warehouse'
      this.$router.push(url)
    },
    getUserInfo() {
      // 调用登录接口
      wx.login({
        success: () => {
          wx.getUserInfo({
            success: (res) => {
              this.userInfo = res.userInfo
            },
          })
        },
      })
    },
    clickHandle(msg, ev) {
      // eslint-disable-next-line
    },
  },
  created() {
    // 调用应用实例的方法获取全局数据
    this.getUserInfo()
  },
}
</script>

<style scoped lang="scss">
@import 'index';
.logout {
  margin-top: 20rpx;
  color: #4a4a4a;
  font-size: 26rpx;
  text-align: right;
}
.copy-right {
  margin-top: 40rpx;
}
.userinfo {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.userinfo-avatar {
  width: 128rpx;
  height: 128rpx;
  margin-right: 20rpx;
  border-radius: 50%;
}

.userinfo-nickname {
  color: #aaa;
}
.form-control {
  display: block;
  padding: 0 12px;
  margin-bottom: 5px;
  border: 1px solid #ccc;
}
.counter {
  display: inline-block;
  margin: 10px auto;
  padding: 5px 10px;
  color: blue;
  border: 1px solid blue;
}
</style>
